/*global pi */
var pathfinding = (function () {
	"use strict";

	var module = {},
		ANI = {IDLE: 0, RUN: 1, ATTACH: 2};

	/* 创建一个演示程序 */
	module.createDemo = function () {
		var demo = {},
			lastTime,
			camera,
			camsys,
			scene,
			getClientSize,
			terrainQuery,
			dragStart,
			i,
			path,
			po,
			pathObjs = [],
			pathStart,
			pathEnd,
			onMouseDown = function (event) { // 鼠标按键按下
				var t, pos, ray,
					mousePos = pi.os.util.getCursorPos(),
					x = mousePos.x,
					y = mousePos.y;

				switch (event.button) {
				case 0: // 左键
					dragStart = {x: x, y: y};
					break;
				case 2: // 右键
					ray = camera.getRay(x / getClientSize().w, y / getClientSize().h);
					pos = terrainQuery(ray).pos;
					pos.y += 1;

					if (pathStart === undefined || pathEnd !== undefined) {
						pathStart = pos;
						pathEnd = undefined;
						for (i = 0; i < pathObjs.length; i++) {
							scene.destroyObj(pathObjs[i]);
						}
						pathObjs = [];
						po = scene.createCube({r: 255, g: 255, b: 0, a: 255});
						po.setPos(pathStart);
						po.setVisible(true);
						pathObjs.push(po);
					} else {
						pathEnd = pos;
						po = scene.createCube({r: 0, g: 0, b: 255, a: 255});
						po.setPos(pathEnd);
						po.setVisible(true);
						pathObjs.push(po);
						path = scene.nav.findPath(pathStart, pathEnd);
						for (i = 0; i < path.length - 1; i++) {
							po = scene.createLine(path[i], path[i + 1], {r: 255, g: 0, b: 0, a: 255});
							po.setVisible(true);
							pathObjs.push(po);
						}
					}
					break;
				}
			},
			onMouseUp = function (event) { // 鼠标按键弹起
				switch (event.button) {
				case 0: // 左键
					dragStart = undefined;
					break;
				case 2: // 右键
					break;
				}
			},
			onMouseMove = function (event) { // 鼠标移动
				var dx, dy;
				if (dragStart === undefined) {
					return;
				}

				dx = event.offsetX - dragStart.x;
				dy = event.offsetY - dragStart.y;
				if (dx === 0 && dy === 0) {
					return;
				}

				dragStart = {x: event.offsetX, y: event.offsetY};
				camsys.rotate(dx / 150);
				camsys.pullup(dy / 150);
			},
			onMouseWheel = function (event) { // 鼠标滚轮
				var dist = event.wheelDelta / 1000 * camsys.getDistance();
				camsys.push(-dist);
			},
			onKeyDown = function (event) { // 键盘按键响应
				var kc = event.keyCode;
				switch (kc) {
				case 112: // f1
					scene.setNavNetVisible(true);
					break;
				}
			},
			drawScene = function () { // 绘制场景
				if (lastTime === 0) {
					lastTime = pi.lang.createDate().getTime();
				}

				// 开始渲染，返回渲染指令缓冲区
				var now = pi.lang.createDate().getTime(),
					buf = pi.render.run.beginRender(),
					timeElapsed = now - lastTime;

				// 更新运动
				pi.scene.movement.update(timeElapsed);

				// 更新摄像机
				camsys.update(timeElapsed);

				// 更新场景
				scene.update(timeElapsed);

				// 渲染场景
				scene.render(camera, buf);

				// 发送渲染指令
				pi.render.run.endRender(buf);

				// 制作场景快照
				scene.taskSnapshoot("lastFrame");

				lastTime = now;
			},
			doSchedule = function () { // 调度场景
				scene.scheduleArea(camera); // 调度场景
				scene.scheduleTerrain(camera); // 调度地块
			};

			// 初始化演示程序
		demo.init = function (doc) {
			pi.mod.require(["pi.lang", "pi.os.util", "pi.scene", "pi.scene.camsys", "pi.scene.query", "pi.scene.movement", "pi.res", "pi.render.run"], function () {
				pi.render.run.init(function (context) {
					// 垃圾回收循环
					pi.lang.setInterval(pi.vcall.gc, 1000);

					// 创建场景
					pi.res.load("demos/pathfinding/json/scene.json",
						pi.res.JSON,
						function (jsonData) {
							var obj;

							// 加载场景
							scene = pi.scene.load(jsonData);
							scene.showAABB = false;
							scene.renderMask = pi.scene.MASK_VISIBLE | pi.scene.MASK_OBSTACLE;

							// 创建摄像机
							camera = scene.createCamera();
							camera.setProjection(45.0 * Math.PI / 180, 1, 0.1, 10000);
							camsys = pi.scene.camsys.createThirdPerson(camera);

							// 设置摄像机目标
							obj = scene.createCube();
							obj.setVisible(true);
							camsys.setParams({yaw: 0, pitch: Math.PI / 8, dist: 50});
							camsys.setAim(obj);

							obj = scene.createCube({r: 64, g: 64, b: 0, a: 255});
							obj.setVisible(true);
							obj.setScale({x: 500, y: 0.01, z: 500});
							obj.setMask(0x00000010);

							// 创建地表高度查询器
							terrainQuery = scene.createHeightQuery();

							pi.browser.resize(pi.vcall.webViewHandle);

							// 场景调度
							pi.lang.setInterval(doSchedule, 1000);

							// 设置应用层的渲染回调
							pi.render.run.setCallback(drawScene, scene.resize);
						});
				});
			});

			// 注册鼠标和键盘事件
			doc.onmousedown = onMouseDown;
			doc.onmouseup = onMouseUp;
			doc.onmousemove = onMouseMove;
			doc.onmousewheel = onMouseWheel;
			doc.onkeydown = onKeyDown;
			getClientSize = function () { return {w: doc.body.clientWidth, h: doc.body.clientHeight}; };
		};

		return demo;
	};

	return module;
}());